package com.pason.onlineshop.mainshop.service.entity.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pason.onlineshop.mainshop.domain.Order;
import com.pason.onlineshop.mainshop.service.entity.IOrderEntityService;
import com.pason.onlineshop.mainshop.service.entity.query.IQueryDataEntityService;
import com.pason.onlineshop.mainshop.service.entity.query.impl.QueryCondition;

@Service("orderEntityService")
@Repository
@Transactional
public class OrderEntityServiceImpl implements IOrderEntityService{
	private Log log = LogFactory.getLog(OrderEntityServiceImpl.class);	
	
	@Autowired(required=true)
	IQueryDataEntityService queryDataService;
	
	@PersistenceContext
	private EntityManager em;
	
	@Transactional(readOnly=true)
	public List<Order> listOrders() {
		List<Order> orders = em.createNamedQuery("Order.listOrders", Order.class).getResultList();
		return orders;
	}
	
	@Transactional(readOnly=true)
	public Order findById(Long id) {
		TypedQuery<Order> query = em.createNamedQuery("Order.findById", Order.class);
		query.setParameter("id", id);
		return query.getSingleResult();
	}
	
	public Order saveOrder(Order order) {
		if (order.getId() == null) { 
			// Insert Order
			log.info("Inserting new order");
			em.persist(order);
		} else {                       
			// Update Order
			em.merge(order);
			log.info("Updating existing order");
		}
		log.info("Order saved with id: " + order.getId());
		return order;
	}

	@Override
	public void deleteOrder(Long id) {
		log.debug("Delete order ["+id+"]");
		em.remove(this.findById(id));
	}
	
	@Transactional(readOnly=true)
	public List<Order> searchOrders(QueryCondition queryCondition) {
		return queryDataService.queryByPropertys(queryCondition);
	}
	
	
}
